/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.activity.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.activity.vo.VEntVo;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.activity.entity.VEnt;
import com.ykht.proj.activity.service.VEntService;
import com.ykht.proj.common.security.annotation.Inner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 企业（客户）表
 *
 * @author csg
 * @date 2021-05-21 14:22:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/vent" )
@Api(value = "vent", tags = "企业（客户）表管理")
@Slf4j
public class VEntController {

    private final  VEntService vEntService;
	private final RemoteUserService remoteUserService;

    /**
     * 企业列表 分页查询
     * @param page 分页对象
     * @param vEntVo 企业（客户）表
     * @return
     */
    @ApiOperation(value = "企业列表 分页查询", notes = "企业列表 分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('activity_vent_view')" )
    public R getVEntPage(Page page, VEntVo vEntVo) {
		log.info("->企业列表分页查询{}{}", page, vEntVo);
		IPage<VEntVo> iPage = vEntService.getVEntPage(page, vEntVo);
		if (null != iPage.getRecords() && iPage.getRecords().size() > 0){
			List<VEntVo> entVoList = iPage.getRecords();
			List<Long> loginIdList = entVoList.stream().map(VEntVo::getLoginId).collect(Collectors.toList());
			List<SysUser> userList = remoteUserService.userByIds(loginIdList);
			entVoList.stream().forEach(ent ->{
				userList.stream().forEach(user ->{
					if (ent.getLoginId().equals(Long.valueOf(user.getUserId()))){
						ent.setUsername(user.getUsername());
					}
				});
			});
			iPage.setRecords(entVoList);
		}
        return R.ok(iPage);
    }


    /**
     * 通过id查询企业（客户）表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('activity_vent_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(vEntService.getById(id));
    }

    /**
     * 新增企业（客户）表
     * @param vEntVo 企业（客户）表
     * @return R
     */
    @ApiOperation(value = "新增企业（客户）表", notes = "新增企业（客户）表")
    @SysLog("新增企业（客户）表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('activity_vent_add')" )
    public R save(@RequestBody VEntVo vEntVo) {
		log.info("->新增企业（客户）表:{}", JSONUtil.toJsonStr(vEntVo));
        return vEntService.saveAndUser(vEntVo);
    }

    /**
     * 修改企业（客户）表
     * @param vEnt 企业（客户）表
     * @return R
     */
    @ApiOperation(value = "修改企业（客户）表", notes = "修改企业（客户）表")
    @SysLog("修改企业（客户）表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('activity_vent_edit')" )
    public R updateById(@RequestBody VEnt vEnt) {
        return R.ok(vEntService.updateById(vEnt));
    }

    /**
     * 通过id删除企业（客户）表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除企业（客户）表", notes = "通过id删除企业（客户）表")
    @SysLog("通过id删除企业（客户）表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('activity_vent_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(vEntService.removeById(id));
    }


	@ApiOperation(value = "校验 企业名称")
	@PostMapping("/checkPlanName")
	public R checkSjName(@RequestBody VEntVo vEntVo) {
		log.info("->校验 企业名称{}", vEntVo);
		VEnt ent = new VEnt().selectOne(Wrappers.lambdaQuery(VEnt.class)
				.eq(!StringUtils.isEmpty(vEntVo.getName()), VEnt::getName, vEntVo.getName()));
		return R.ok(ent == null ? true : ent.getId().equals(vEntVo.getId()) ? true : false);
	}



	/**
	 * 根据 登录ID（用户ID） 获取企业列表
	 *
	 * @return R
	 */
	@ApiOperation("根据 登录ID（用户ID） 获取企业列表")
	@PostMapping("/getByLoginId/{loginId}")
	@Inner
	public List<VEnt> getByLoginId(@PathVariable("loginId") Integer loginId) {
		return vEntService.list(Wrappers.lambdaQuery(VEnt.class)
				.eq(VEnt::getLoginId, loginId).eq(VEnt::getDelFlag, 0));
	}

}
